package com.xxx.control.activity

import android.app.Activity
import android.content.Intent
import android.os.Bundle
import android.view.View
import android.widget.AdapterView
import android.widget.ArrayAdapter
import com.blankj.utilcode.util.SPUtils
import com.gg.reader.api.protocol.gx.ActionParamSuccess
import com.gg.reader.api.protocol.gx.MsgAppGetEasAlarm
import com.gg.reader.api.protocol.gx.MsgAppSetEasAlarm
import com.lxj.xpopup.XPopup
import com.xxx.control.R
import com.xxx.control.application.App
import com.xxx.control.application.SetInfo
import com.xxx.control.base.BaseVMActivity
import com.xxx.control.base.NoViewModel
import com.xxx.control.base.ext.clickWithTrigger
import com.xxx.control.constant.Constant
import com.xxx.control.databinding.ActivitySettingBinding
import com.xxx.control.net.RetrofitManager
import com.xxx.control.utils.AlarmUtils
import com.xxx.control.utils.ReaderClient

class SettingActivity : BaseVMActivity<ActivitySettingBinding, NoViewModel>() {

    var filterType = 0

    private var currentHour : Int = 0
    private var currentMinute : Int = 0

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)

        val app = application as App

        val dire = SPUtils.getInstance().getBoolean(Constant.DIRE_IN_ONE_TO_ZERO, false)
        mBinding.rgDire.check(if (dire) R.id.rb_dire_in else R.id.rb_dire_out)
        mBinding.rgServer.check(if (SetInfo.isOffline()) R.id.rb_offline else R.id.rb_online)
        //mBinding.tvSerial.text = SPUtils.getInstance().getString(Constant.SERIAL_PORT, "/dev/ttyS0")
        mBinding.etIpAddress.setText(SPUtils.getInstance().getString(Constant.IP_ADDRESS, "http://140.143.171.108:8030/"))

        // 页面初始化获取读写器IP地址
        mBinding.tvReaderIp.setText(SPUtils.getInstance().getString(Constant.READER_IP, ""))
        // 页面初始化获取读写器2IP地址
        mBinding.tvReader2Ip.setText(SPUtils.getInstance().getString(Constant.READER_SECOND_IP, ""))

        // 小时
        mBinding.spinnerHour.apply {
            // 定义小时数据源（24小时制）
            val hours = (0..23).map { "%02d".format(it) }

            adapter = ArrayAdapter(
                this@SettingActivity,
                android.R.layout.simple_spinner_item,
                hours  // 传入格式化后的数据集合
            ).also {
                it.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item)
            }

            onItemSelectedListener = object : AdapterView.OnItemSelectedListener {
                override fun onItemSelected(p0: AdapterView<*>?, p1: View?, pos: Int, p3: Long) {
                    // 选中项处理逻辑
                    currentHour = hours[pos].toInt()
                }
                override fun onNothingSelected(p0: AdapterView<*>?) {}
            }
        }

        // 分钟
        mBinding.spinnerMinute.apply {
            // 定义分钟数据源（60分）
            val minutes = (0..55 step 5).map { "%02d".format(it) }

            adapter = ArrayAdapter(
                this@SettingActivity,
                android.R.layout.simple_spinner_item,
                minutes  // 传入格式化后的数据集合
            ).also {
                it.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item)
            }

            onItemSelectedListener = object : AdapterView.OnItemSelectedListener {
                override fun onItemSelected(p0: AdapterView<*>?, p1: View?, pos: Int, p3: Long) {
                    // 选中项处理逻辑
                    currentMinute = minutes[pos].toInt()
                }
                override fun onNothingSelected(p0: AdapterView<*>?) {}
            }
        }

        // 页面初始化获取存储的定时清空时间【小时】
        mBinding.spinnerHour.setSelection(SPUtils.getInstance().getInt(Constant.CURRENT_HOUR_INDEX,0))
        // 页面初始化获取存储的定时清空时间【分钟】
        mBinding.spinnerMinute.setSelection(SPUtils.getInstance().getInt(Constant.CURRENT_MINUTE_INDEX,0))

//        mBinding.tvSerial.clickWithTrigger {
//            XPopup.Builder(this)
//                .atView(it)
//                .asAttachList(
//                    arrayOf("/dev/ttyXRUSB2", "/dev/ttyS0", "/dev/ttyS1", "/dev/ttyS2", "/dev/ttyS3", "/dev/ttyS4"),
//                    null
//                ) { position, text ->
//                    mBinding.tvSerial.text = text
//                }.show()
//        }

        mBinding.tvFilter.clickWithTrigger {
            XPopup.Builder(this)
                .atView(it)
                .asAttachList(
                    arrayOf("EPC", "TID", "USER"),
                    null
                ) { position, text ->
                    filterType = position
                    mBinding.tvFilter.text = text
                }.show()
        }

        mBinding.tvReadEas.clickWithTrigger {
            val getEasAlarm = MsgAppGetEasAlarm()
            app.client.sendSynMsg(getEasAlarm)
            app.clientSecond.sendSynMsg(getEasAlarm)
            if (getEasAlarm.rtCode.toInt() == 0x00) {
                val isOn = getEasAlarm.alarmSwitch == 1
                if (isOn) {
                    mBinding.rbOn.setChecked(true)
                } else {
                    mBinding.rbOff.setChecked(true)
                }

                mBinding.tvFilter.text = when (getEasAlarm.filterData) {
                    0 -> "EPC"
                    1 -> "TID"
                    2 -> "USER"
                    else -> "EPC"
                }

                mBinding.etStartByte.setText(getEasAlarm.start.toString())
                mBinding.etMatch.setText(getEasAlarm.hexContent)
                mBinding.etMask.setText(getEasAlarm.hexMask)

//                val actionParamSuccess = getEasAlarm.success
//                if (actionParamSuccess != null) {
//                    alarmTime = actionParamSuccess.keepTime
//                    gpo = actionParamSuccess.gpo1
//                }
//                etAlarmTime.setText(alarmTime.toString())
//                if (gpo == 1) {
//                    rbGpoHigh.setChecked(true)
//                } else {
//                    rbGpoLower.setChecked(true)
//                }
            } else {
                toast("查询失败")
            }
        }

        mBinding.tvSetEas.clickWithTrigger {
//            val gpo = if (mBinding.rbOn.isChecked) 1 else 0
            val start = mBinding.etStartByte.text.toString()
            val matchContent = mBinding.etMatch.text.toString()
            val mask = mBinding.etMask.text.toString()

            var alarmTime = 1
            if (alarmTime < 1) {
                alarmTime = 1
            } else if (alarmTime > 4) {
                alarmTime = 4
            }
            val easAlarm = MsgAppSetEasAlarm()
            //1开启  0关闭
            easAlarm.alarmSwitch = if (mBinding.rbOn.isChecked) 1 else 0
            //0=epc   1=tid  2=user
            easAlarm.filterData = filterType
            //起始
            try {
                easAlarm.start = start.toInt()
            } catch (e: Exception) {
                easAlarm.start = 11
                e.printStackTrace()
            }
            //匹配
            easAlarm.hexContent = matchContent
            //掩码
            easAlarm.hexMask = mask

            val actionParamSuccess = ActionParamSuccess()
            actionParamSuccess.gpo1 = 1
//            actionParamSuccess.gpo2 = 1
            actionParamSuccess.keepTime = alarmTime
            easAlarm.success = actionParamSuccess

            app.client.sendSynMsg(easAlarm)
            app.clientSecond.sendSynMsg(easAlarm)

            if (easAlarm.rtCode.toInt() == 0x00) {
                toast("EAS设置成功")
            } else {
                toast("EAS设置失败")
            }
        }

        mBinding.btSave.clickWithTrigger {
            SetInfo.setOffline(mBinding.rbOffline.isChecked)
            SPUtils.getInstance().put(Constant.DIRE_IN_ONE_TO_ZERO, mBinding.rbDireIn.isChecked)
            //SPUtils.getInstance().put(Constant.SERIAL_PORT, mBinding.tvSerial.text.toString())
            SPUtils.getInstance().put(Constant.IP_ADDRESS, mBinding.etIpAddress.text.toString())
            SPUtils.getInstance().put(Constant.READER_IP, mBinding.tvReaderIp.text.toString())
            SPUtils.getInstance().put(Constant.READER_SECOND_IP, mBinding.tvReader2Ip.text.toString())

            SPUtils.getInstance().put(Constant.CURRENT_HOUR,currentHour)
            SPUtils.getInstance().put(Constant.CURRENT_MINUTE,currentMinute)

            SPUtils.getInstance().put(Constant.CURRENT_HOUR_INDEX,mBinding.spinnerHour.selectedItemPosition)
            SPUtils.getInstance().put(Constant.CURRENT_MINUTE_INDEX,mBinding.spinnerMinute.selectedItemPosition)
            RetrofitManager.mRetrofitManager = null

            setResult(RESULT_OK) // 设置返回结果
            finish() // 关闭当前Activity
        }

//        val reconnectTime = mBinding.etReconnectTime.text.t




    }


}